﻿using SuperX.DataCenterService.App_Start;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerUI;
using System.Text.Json;
using System;
using System.Text.Json.Serialization;
using Newtonsoft.Json.Serialization;

namespace SuperX.DataCenterService.WebAPI
{
    public class WebHostCore
    {
        public WebHostCore(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //添加cors 服务 配置跨域处理
            services.AddCors(options =>
            {
                options.AddPolicy
                (name: "any",
                    builde =>
                    {
                        builde.WithOrigins("*", "*", "*")
                        .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                    }
                );
            });
            //添加对象序列化程序为Newtonsoft.Json
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
            services.ConfigureSwaggerUp();
            services.AddMvc(options =>
            {
                options.Filters.Add<ApiExceptionAttribute>();
                options.Filters.Add<ApiResponseAttribute>();
                options.EnableEndpointRouting = false;
            }).AddJsonOptions(options =>
            {
                //空字段不响应Response
                options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                //时间格式化响应
                options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors("any");
            app.UseRouting();
            app.UseAuthorization();
            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "api-docs/{documentName}/swagger.json";
            });
            //启用中间件服务对swagger-ui，指定Swagger JSON终结点
            app.UseSwaggerUI(c =>
            {
                c.DocExpansion(DocExpansion.None);
                c.SwaggerEndpoint("/api-docs/v1/swagger.json", "SuperX-IoT API V1");
            });
            app.UseMvc();
        }
    }

    /// <summary>
	/// 设置Json默认DateTime格式化
	/// </summary>
	public class DateTimeJsonConverter : JsonConverter<DateTime>
    {
        private readonly string Format;

        public DateTimeJsonConverter(string format)
        {
            Format = format;
        }

        public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
        {
            writer.WriteStringValue(date.ToString(Format));
        }

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.ParseExact(reader.GetString(), Format, null);
        }
    }
}